<template>
  <utilPage>
    <template #header>
      <!-- 搜索 -->
      <div class="font-size-3 text-#303133">

        ID<el-input v-model="keyWord" style="max-width: 280px" placeholder="请输入关键字" class="input-with-search ml-3"
          @keyup.enter="searchList">
        </el-input>

        姓名<el-input v-model="keyWord" style="max-width: 280px" placeholder="请输入关键字" class="input-with-search ml-3"
          @keyup.enter="searchList">
        </el-input>

        账号<el-input v-model="keyWord" style="max-width: 280px" placeholder="请输入关键字" class="input-with-search ml-3"
          @keyup.enter="searchList">
        </el-input>

        <el-button @click="searchList" type="primary">
          搜索
        </el-button>
      </div>

      <div class="mt-6">
        <!-- 添加 -->
        <add @finishAdd=getList() />
        <!-- 批量删除 -->
        <el-button type="danger" class="ml-8 mb-5" @click="delSelect()">
          <el-icon class="mr-1">
            <Delete />
          </el-icon>
          批量删除
        </el-button>
      </div>
    </template>

    <div>
      <!-- 列表部分 -->
      <el-table :data="list" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" width="100">
          <template #default="scope">
            <!-- {{ scope.$index + 1 }} -->
            {{ startIndex + scope.$index }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="100" />
        <el-table-column prop="gender" label="性别" width="100" />
        <el-table-column prop="account" label="账号" />
        <el-table-column prop="password" label="密码" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="createdAt" label="创建时间">
          <template #default="row">
            {{ dayjs(row.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" @click="editRow(row)">编辑</el-button>
            <el-button type="danger" @click="delRow(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 底部分页 -->
    <template #footer v-if="showPagination">
      <div class="el-pagination-footer">
        <el-pagination :total="total" v-model:page-size="pagesize" :page-sizes="[8, 10, 20, 30, 50]"
          v-model:current-page="curpage" layout="total, prev, pager, next, sizes" @change="handlePageChange" />
      </div>
    </template>

    <!-- 抽屉 -->
    <el-drawer v-model="showEdit" title="用户信息修改" :with-header="true">
      <el-form label-width="100px" :rules="rules" :model="customer">

        <el-form-item label="用户名" prop="username">
          <el-input placeholder="请输入用户名" v-model="customer.username" />
        </el-form-item>

        <el-form-item label="账号" prop="account">
          <el-input placeholder="请输入账号" v-model="customer.account" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input placeholder="请输入账号" v-model="customer.password" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="customer.gender" placeholder="请选择性别">
            <el-option label="女" value="女" />
            <el-option label="男" value="男" />
          </el-select>
        </el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input placeholder="请输入手机号码" v-model="customer.phone" />
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input placeholder="请输入地址" v-model="customer.address" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="quxiao">取消</el-button>
        <el-button type="primary" @click="editCustomer">确定</el-button>
      </template>
    </el-drawer>

  </utilPage>
</template>


<script setup lang="ts">
import add from '../Customer/component/add.vue'
import { getCustomerList, searchCustomerList, delterCustomer, delSelectCustomer,updateCustomer } from '@/api/Customer.ts'
import { dayjs, ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref } from 'vue'

const showPagination = ref(true)
// 定义响应式变量 list为列表数据 total为总数
const list = ref([])
const total = ref(0)
// 一页显示多少条
const pagesize = ref(8)
// 当前页码
const curpage = ref(1)
// 获取输入框的值 用于搜索
const keyWord = ref<any>('')

// 存储每页的开始序号
const startIndex = ref<number>(1);

// 存储选中的行
const selectedRows = ref<any>([])

// 获取勾选中的用户数据
const handleSelectionChange = (value) => {
  selectedRows.value = value;
  console.log(selectedRows.value);
};

// 处理页面改变
const handlePageChange = (page: number, limit: number) => {
  curpage.value = page
  pagesize.value = limit
  startIndex.value = (page - 1) * limit + 1
  // 获取新的数据列表
  getList()
}

// 列表数据
const getList = () => {
  getCustomerList({ page: curpage.value, limit: pagesize.value }).then(res => {
    // 请求服务器向数据库中得到的列表数据
    // console.log('请求得到的列表数据是111', res);
    if (res.data.success) {
      // 获取列表数据
      list.value = res.data.data.data;
      // 数据总条数
      total.value = res.data.data.total
    }

  })
}

//删除
const delRow = (id: number) => {
  //  const res = delterCustomer(id)
  //   console.log(res);
  ElMessageBox.confirm(
    '是否删除此用户?',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      // const res = delterCustomer(id)
      // console.log(res);
      const res = await delterCustomer(id);
      if (res.data.success) {
        ElMessage.success('删除成功');
        // 删除成功之后再次更新页面
        getList()
      }
    })
    .catch(() => {
    })
}

//批量删除
const delSelect = () => {
  console.log(selectedRows.value);
  if (!selectedRows.value.length) {
    ElMessage.warning('请至少选择一行进行删除');
    return;
  }
  ElMessageBox.confirm(
    '是否批量删除用户?',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const ids = selectedRows.value.map(item => item.id);
      const res = await delSelectCustomer(ids);
      if (res.data.success) {
        ElMessage.success('删除成功');
        // 清空已选中的行
        selectedRows.value = [];
        // 删除成功之后再次更新页面
        getList()
      }
    })
    .catch(() => {
    })
}

//搜索
const searchList = () => {
  // 当输入框被清空时，再次调用getList()函数，反之则根据id来查询数据并渲染到页面上
  if (keyWord.value === '') {
    getList();
    showPagination.value = true;
  } else {
    searchCustomerList({ id: keyWord.value }).then(res => {
      console.log('请求得到的列表数据是', res);
      if (res.data.success) {
        list.value = [res.data.data];
      }
      showPagination.value = false;
    })
  }
}

//编辑
interface Customer {
  username: String, //用户名
  account: String, //账号
  password: String, //密码
  gender: String, //性别
  address: String, //地址
  phone: String, //手机号
  profile?: String, //头像
}
const customer = ref<Customer>({
  username: '',
  account: '',
  password: '',
  gender: '',
  address: '',
  phone: '',
  profile: '',

})
const showEdit = ref(false)
const originalData = ref<any>(null);
//控制抽屉的显示与隐藏  
const editRow = (row: any) => {
  const originalData = JSON.parse(JSON.stringify(row));
  customer.value = originalData;
  showEdit.value = true
  // 一点进去就是原来的数据
  // customer.value = row
}
// 修改数据
const editCustomer = async () => {
  const res = await updateCustomer(customer.value)
  if (res.data.success) {
    ElMessage.success('修改成功')
    showEdit.value = false
    getList()
  }
}
// 取消
const quxiao = () => {
  showEdit.value = false
  customer.value = JSON.parse(JSON.stringify(originalData));
}



// 表单校验规则
const rules = ref({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' }
  ],
  account: [
    { required: true, message: '账户不能为空', trigger: 'blur' },

  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
  ],
  gender: [
    { required: true, message: '性别不能为空', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '手机号码不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '地址不能为空', trigger: 'blur' },
  ]
})


onMounted(() => {
  getList();
})

</script>


<style lang="less" scoped>
.el-table {
  margin-top: 10px;
}

// ::v-deep被弃用 用他会抛出警告
:deep(.el-table__cell) {
  text-align: center;
}

.el-pagination {
  margin-top: 20px;
}

.input-with-search {
  margin-right: 10px;
  width: 200px;
  outline: none;
}
</style>